package com.study.showpinyin.controller;

import com.github.stuxuhai.jpinyin.ChineseHelper;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 通过后台转换
 *  依赖为
 *  <dependency>
 *             <groupId>com.github.stuxuhai</groupId>
 *             <artifactId>jpinyin</artifactId>
 *             <version>1.0</version>
 *         </dependency>
 *  不清楚为啥1.0以上的下不下来
 */
@RestController
@ResponseBody
public class BgTransform {
    @RequestMapping("/transform")
    @ResponseBody
    public String transform(String str) {
        StringBuffer ret = new StringBuffer();
//        PinyinHelper.convertToPinyinString(str, ",", PinyinFormat.WITH_TONE_MARK); // nǐ,hǎo,shì,jiè
//        PinyinHelper.convertToPinyinString(str, ",", PinyinFormat.WITH_TONE_NUMBER); // ni3,hao3,shi4,jie4
//        PinyinHelper.convertToPinyinString(str, ",", PinyinFormat.WITHOUT_TONE); // ni,hao,shi,jie
//        PinyinHelper.getShortPinyin(str); // nhsj
        String py = PinyinHelper.convertToPinyinString(str, "|", PinyinFormat.WITH_TONE_MARK);
        System.out.println(py);
        char[] charArray = str.toCharArray();
        String[] pyArray = py.split("\\|");
        int j = 0;
        for (int i = 0; i < pyArray.length; i++) {
            if (ChineseHelper.isChinese(charArray[j])) {
                ret.append("<ruby>" + charArray[j] + "<rt>" + pyArray[i] + "</rt></ruby>");
                j++;
            } else {
                for (int k = j; k < charArray.length; k++) {
                    if (ChineseHelper.isChinese(charArray[j])) {
                        break;
                    }
                    ret.append(charArray[k]);
                    j++;
                }
            }
        }
        return ret.toString();
    }
}
